program HeapySort;

{$APPTYPE CONSOLE}

uses
  SysUtils;
var
  i, m, k, N: integer;
  arr: array of integer;

procedure Heapify(num: integer);
var
a, b, c, t: integer;
begin
  while (1=1) do
  begin
    c:=arr[num];
    a:=2000000000;
    b:=2000000000;
    if (2*num+1<N) then
      a:=arr[2*num+1];
    if (2*num+2<N) then
      b:=arr[2*num+2];
    if (a<=b) and (a<c) then
    begin
      t:=arr[2*num+1];
      arr[2*num+1]:=arr[num];
      arr[num]:=t;
      num:=2*num+1;
    end
    else
    begin
      if (b<=a) and (b<c) then
      begin
        t:=arr[2*num+2];
        arr[2*num+2]:=arr[num];
        arr[num]:=t;
        num:=2*num+2;
      end
      else
        break;
    end;
  end;
end;

begin
  N:=10;
  setlength(arr, N);
  randomize;
  for i:=0 to N-1 do
    arr[i]:=random(N+10);
  for i:=0 to N-1 do
    write(arr[i], ' ');
  writeln;
  for i:=N-1 downto 0 do
    Heapify(i);
  m:=N;
  for i:=0 to m-1 do
  begin
    k:=arr[N-1];
    arr[N-1]:=arr[0];
    arr[0]:=k;
    write(arr[N-1], ' ');
    N:=N-1;
    Heapify(0);
  end;
  N:=m;
  readln;
end.
